import React from "react";
import { Button, Popover, Tag } from "antd";
import { useDispatch, useSelector } from "react-redux";
import { setTheme } from "../store/theme";
import { SkinOutlined } from "@ant-design/icons";

const ThemeSelector = () => {
  const dispatch = useDispatch();
  const currentTheme = useSelector((state) => state.theme.currentTheme);
  const themes = useSelector((state) => state.theme.themes);

  const handleThemeChange = (theme) => {
    dispatch(setTheme(theme));
    // 应用主题到body
    applyTheme(themes[theme]);
  };

  const applyTheme = (theme) => {
    const root = document.documentElement;
    Object.keys(theme).forEach((key) => {
      if (key !== "name") {
        root.style.setProperty(`--${camelToKebab(key)}`, theme[key]);
      }
    });
  };

  const camelToKebab = (str) => {
    return str.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
  };

  // 获取当前主题的颜色用于标签显示
  const getCurrentThemeColor = () => {
    const theme = themes[currentTheme];
    if (!theme) return "#1890ff";
    
    // 根据主题名称返回对应的颜色，确保良好的对比度
    switch(currentTheme) {
      case "dark": return "#000000";
      case "blue": return "#001529";
      case "green": return "#135200";
      case "purple": return "#391085";
      case "orange": return "#874d00";
      case "pink": return "#87004d";
      case "cyan": return "#00474f";
      default: return "#000000";
    }
  };

  // 创建主题选项按钮
  const themeButtons = Object.keys(themes).map((key) => (
    <Button
      key={key}
      type={currentTheme === key ? "primary" : "default"}
      onClick={() => handleThemeChange(key)}
      style={{ 
        margin: "4px", 
        width: "100%",
        textAlign: "left",
        justifyContent: "flex-start"
      }}
    >
      {themes[key].name}
    </Button>
  ));

  return (
    <Popover
      content={
        <div style={{ padding: "8px" }}>
          {themeButtons}
        </div>
      }
      title="选择皮肤"
      trigger="click"
    >
      <Button icon={<SkinOutlined />} size="small">
        <Tag color={getCurrentThemeColor()} style={{ marginLeft: 8 }}>
          {themes[currentTheme]?.name || "默认"}
        </Tag>
      </Button>
    </Popover>
  );
};

export default ThemeSelector;